var SPLIT1 = "W+";
var SPLIT2 = "-";
function readExtends(obj,bn){
	var gestationalWeeks = obj.gestationalWeeks;
	if(gestationalWeeks){
		var gwks = gestationalWeeks.split(/W\+/);
		$("#gestationalWeeks1").val(gwks[0]);
		$("#gestationalWeeks2").val(gwks[1])
	}
	//处理免费类型字段，该字段在info表上
	if(obj.sampleInfos && obj.sampleInfos.length>0){
		var freeType = obj.sampleInfos[0].freeType;
		if(freeType){
			$("#freeType").val(freeType);
		}
	}
	if(obj.ntGestationalWeeks){
		var value = obj.ntGestationalWeeks;
		if(value.indexOf('w')>=0 && value.indexOf('d')>=0){
			$("#ntGestationalWeeks1").val(value.substring(0,value.indexOf('w')));
			$("#ntGestationalWeeks2").val(value.substring(value.indexOf('w')+1,value.indexOf('d')));
		}else if(value.indexOf('w')<0 && value.indexOf('d')>=0){
			$("#ntGestationalWeeks2").val(value.substring(0,value.indexOf('d')));
		}else if(value.indexOf('w')>=0 && value.indexOf('d')<0){
			$("#ntGestationalWeeks1").val(value.substring(0,value.indexOf('w')));
		}
	}
	if(obj.personalReproductiveHistory){
		var arr = obj.personalReproductiveHistory.split(SPLIT2);
		$("#personalReproductiveHistory1").val(arr[0]);
		$("#personalReproductiveHistory2").val(arr[1]);
	}
}
function saveExtends(bn){
	//处理孕周字段
	var gestationalWeeks1 = $("#gestationalWeeks1").val();
	var gestationalWeeks2 = $("#gestationalWeeks2").val();
	bn.obj.gestationalWeeks = gestationalWeeks1+"W+"+gestationalWeeks2;
	//处理免费类型字段，该字段在info表上
	var infos = bn.obj.sampleInfos;
	for(var i=0;i<infos.length;i++){
		infos[i]["freeType"] = $("#freeType").val();
	}
	//超声检测孕周
	var value = '';
	if($("#ntGestationalWeeks1").val()){
		value += $("#ntGestationalWeeks1").val()+'w';
	}
	if($("#ntGestationalWeeks2").val()){
		value += $("#ntGestationalWeeks2").val()+'d';
	}
	bn.obj.ntGestationalWeeks = value;
	//生育史
	var v1 = $("#personalReproductiveHistory1").val()||'';
	var v2 = $("#personalReproductiveHistory2").val()||'';
	bn.obj.personalReproductiveHistory = v1+SPLIT2+v2;
}
temp.validateAbs = function(m){
	var msg = '';
	if(m) msg += m;
	
	var g1 = $("#gestationalWeeks1").val();
	var g2 = $("#gestationalWeeks2").val();
	if(!g1 && !g2){
		msg += '<li>孕周不能为空!</li>';
	}
	return msg;
}
$.event.special.valuechange = {
	teardown : function(namespaces) {
		$(this).unbind('.valuechange');
	},
	handler : function(e) {
		$.event.special.valuechange.triggerChanged($(this));
	},
	add : function(obj) {
		$(this).on('keyup.valuechange cut.valuechange paste.valuechange input.valuechange',
				obj.selector, $.event.special.valuechange.handler);
	},
	triggerChanged : function(element) {
		var current = element[0].contentEditable === 'true' ? element.html() : element.val()
		, previous = typeof element.data('previous') === 'undefined' ? element[0].defaultValue : element.data('previous');
		if (current !== previous) {
			element.trigger('valuechange', [ element.data('previous') ]);
			element.data('previous', current);
		}
	}
}
$(function(){
	if(isChrome){
		$('#bloodDate').on('valuechange', function (e, previous) {
			autoGestationalWeeks();
	    	 $("#applyTime").val($("#bloodDate").val());
	    });
		$('#lmp').on('valuechange',function(e,previous){
			$("#edd").val(operationEdd($('#lmp').val()));
			autoGestationalWeeks();
		})
	}else{
		$('#bloodDate').datebox({
		    onSelect: function(date){
		    	autoGestationalWeeks();
		    	$("#applyTime").datebox('setValue',date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate());
		    }
		});
		$('#lmp').datebox({
		    onSelect: function(date){
		    	autoGestationalWeeks();
		    	$("#edd").datebox('setValue',operationEdd(date.getFullYear()+"-"+((date.getMonth()+1)>=10?(date.getMonth()+1):"0"+(date.getMonth()+1))+"-"+(date.getDate()>=10?date.getDate():"0"+date.getDate())));
		    }
		});
	}
	
	$("#idCard").on('valuechange', function (e, previous) {
		autoBirthDayAndAge();
	});
/*	$("#healthCareNumber").on('valuechange',function(e,previous){
		var newValue = $("#healthCareNumber").val();
		if(newValue && newValue.length==19){
			if(/^\d{19}$/.test(newValue)){
				autoInfoByHealthNum(newValue);
			}else{
				sysMsgShow('保健编号格式非法');
			}
		}
	});*/
	
	$("#trisomy21").on('valuechange', function (e, previous) {
		autoMotherSerumRisk();
	});
	$("#trisomy18").on('valuechange', function (e, previous) {
		autoMotherSerumRisk();
	});
});

function autoGestationalWeeks(){
	var lmpDate = "";
	var bloodDate = ""
	if(isChrome){
		if($("#lmp").val()){
			lmpDate = $("#lmp").val();
		}
		if($("#bloodDate").val()){
			bloodDate = $("#bloodDate").val();
		}
	}else {
		if($("#lmp").datebox("getValue")){
			lmpDate = $("#lmp").datebox("getValue");
		}
		if($("#bloodDate").datebox("getValue")){
			bloodDate = $("#bloodDate").datebox("getValue");
		}
	}
	
	var lmpDay = Math.abs(new Date(Date.parse(lmpDate.replace(/-/g,  "/"))));
	var bloodDay = Math.abs(new Date(Date.parse(bloodDate.replace(/-/g,  "/"))));
	if(bloodDay>=lmpDay){
		console.log(((bloodDay-lmpDay)/(1000 * 60 * 60 * 24))%7);
		$("#gestationalWeeks1").val("");
		$("#gestationalWeeks2").val("");
			if(((bloodDay-lmpDay)/(1000 * 60 * 60 * 24))%7==0){
				$("#gestationalWeeks1").val(((bloodDay-lmpDay)/(1000 * 60 * 60 * 24))/7);
			}else {
				var weeks = (((bloodDay-lmpDay)/(1000 * 60 * 60 * 24)-(((bloodDay-lmpDay)/(1000 * 60 * 60 * 24))%7)))/7;
				var days = ((bloodDay-lmpDay)/(1000 * 60 * 60 * 24))%7;
				$("#gestationalWeeks1").val(weeks);
				$("#gestationalWeeks2").val(days);
			}
	};
	
}

function autoMotherSerumRisk(){
	var TRISOMY21 = 0;
	var TRISOMY18 = 0;
	var value18 = 0;
	var value21 = 0;
	if($("#trisomy18").val()){
		TRISOMY18 = parseInt($("#trisomy18").val());
	}
	if($("#trisomy21").val()){
		TRISOMY21 = parseInt($("#trisomy21").val());
	}
	if(parseInt(0)<parseInt(TRISOMY18)&&parseInt(TRISOMY18)<=parseInt(350)){
		value18 = 3;
	}else if(parseInt(TRISOMY18)>parseInt(350)&&parseInt(TRISOMY18)<=parseInt(1000)){
		value18 = 2;
	}else if(parseInt(TRISOMY18)>parseInt(1000)){
		value18 = 1
	}
	if(parseInt(0)<parseInt(TRISOMY21)&&parseInt(TRISOMY21)<=parseInt(270)){
		value21 = 3;
	}else if(parseInt(TRISOMY21)>parseInt(270)&&parseInt(TRISOMY21)<=parseInt(1000)){
		value21 = 2;
	}else if(parseInt(TRISOMY21)>parseInt(1000)){
		value21 = 1
	}
	$("input[id^='motherSerumRisk_']").prop("checked",false);
	if(parseInt(value21)>parseInt(value18)){
		if(value21==3){
			$("#motherSerumRisk_0").prop("checked",true);
		}else if(value21==2){
			$("#motherSerumRisk_2").prop("checked",true);
		}else if(value21==1){
			$("#motherSerumRisk_1").prop("checked",true);
		}
	}else{
		if(value18==3){
			$("#motherSerumRisk_0").prop("checked",true);
		}else if(value18==2){
			$("#motherSerumRisk_2").prop("checked",true);
		}else if(value18==1){
			$("#motherSerumRisk_1").prop("checked",true);
		}
	}
}
function operationEdd(date){
	if(date.split('-')[1]<4){
		return addMonth(addDay(date,7),9);
	}else {
		return deleteMonth(addDay(date,7),3);
	}
}
//月份
function addMonth(sDate, num) {
    var aYmd = sDate.split('-');
    var dt = new Date(Date.parse(sDate.replace(/-/g,  "/")))
    //var dt = new Date(aYmd[1] + '-' + aYmd[2] + '-' + aYmd[0]); //转换为MM-DD-YYYY格式   
    dt.setMonth(dt.getMonth() + num);
    var y = dt.getFullYear();
    var m = dt.getMonth()+ 1;
    var d = dt.getDate();
    if (m == 0) { m = 12; y = y - 1; }

    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '-' + m + '-' + d;
}
function deleteMonth(sDate, num){
	//var aYmd = sDate.split('-');
	var dt = new Date(Date.parse(sDate.replace(/-/g,  "/")))
	//var dt = new Date(aYmd[1] + '-' + aYmd[2] + '-' + aYmd[0]); //转换为MM-DD-YYYY格式   
	console.log(dt);
    dt.setMonth(dt.getMonth() - num);
    dt.setFullYear(dt.getFullYear()+1);
    var y = dt.getFullYear();
    var m = dt.getMonth()+1;
    var d = dt.getDate();
    if (m == 0) { m = 12; y = y - 1; }

    if (m < 10) m = '0' + m;
    if (d < 10) d = '0' + d;
    return y + '-' + m + '-' + d;
}

//追加日
function addDay(dateTemp, days) {  
    var aYmd = dateTemp.split("-");  
    var nDate = new Date(Date.parse(dateTemp.replace(/-/g,  "/")))
   // var nDate = new Date(aYmd[1] + '-' + aYmd[2] + '-' + aYmd[0]); //转换为MM-DD-YYYY格式    
    var millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000);  
    var rDate = new Date(millSeconds);  
    var year = rDate.getFullYear();  
    var month = rDate.getMonth() + 1;  
    if (month < 10) month = "0" + month;  
    var date = rDate.getDate();  
    if (date < 10) date = "0" + date;  
    return (year + "-" + month + "-" + date);  
}  
/**
 * 根据保健编号调用后台接口获取相关信息
 */
function autoInfoByHealthNum(healthNum){
	$.ajax({
		async : true,
		cache:false,
		type: 'POST',
		dataType : "json",
		url:'wechat/getGravidaHealthInfo.action',
		data:{
			"healthInfo.healthNum":healthNum
		},
    	success:function(data){
    		var json = data.object;
    		if(json.name){
    			setVl('sampleName',json.name);
    		}
    		if(json.cardId){
    			setVl('idCard',json.cardId);
    		}
    		if(json.mobile){
    			setVl('motherPhoneNum',json.mobile);
    		}
    		if(json.birthDate){
    			if(isChrome){
    				setVl('birthDate',json.birthDate);
    			}else{
    				$("#birthDate").datebox('setValue',json.birthDate);
    			}
    		}
    		if(json.age){
    			setVl('motherAge',json.age);
    		}
    		if(json.weight){
    			setVl('bodyWeight',json.weight);
    		}
    		if(json.height){
    			setVl('bodyHeight',json.height);
    		}
    		if(json.lastMenstrualPeriod){
    			setVl('lmp',json.lastMenstrualPeriod);
    		}
    		if(json.ivfFlag){
    			setVl('adosculation',json.ivfFlag);
    		}
    		if(json.gravidityTimes){//孕次
    			setVl('personalReproductiveHistory1',json.gravidityTimes);
    		}
    		if(json.parityTimes){
    			setVl('personalReproductiveHistory2',json.parityTimes);
    		}
    		if(json.abortionTimes){
    			setVl('naturalAbortionNum',json.abortionTimes);
    		}
    	}
	});
}
/**
 * 根据身份证号码自动解析生日和年龄
 */
function autoBirthDayAndAge(){
	var newValue = $("#idCard").val();
	if(newValue.length==18){
		//430726198810243118
		var birthday = newValue.substring(6,14);
		if(isChrome){
			$("#birthDate").val(birthday.substring(0,4)+"-"+birthday.substring(4,6)+"-"+birthday.substring(6));
		}else{
			$('#birthDate').datebox('setValue',birthday.substring(0,4)+"-"+birthday.substring(4,6)+"-"+birthday.substring(6));
		}
		$("#motherAge").val(new Date().getFullYear()-Number(birthday.substring(0,4)));
		$("#birthDate").trigger('valuechange');
		$("#motherAge").trigger('valuechange');
	}
}